package ar.com.cooker.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import ar.com.cooker.dao.IngredientDao;
import ar.com.cooker.model.Ingredient;
import ar.com.cooker.model.Recipe;

@Repository
@Transactional
public class IngredientDaoImpl implements IngredientDao {

	private EntityManager entityManager;

	@Override
	public void delete(Integer id) {
		Ingredient i = getEntityManager().find(Ingredient.class, id);
		getEntityManager().remove(i);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Ingredient> findAll() {
		Query q = getEntityManager().createQuery("FROM Ingredient i");
		return q.getResultList();
	}

	@Override
	public Ingredient findById(Integer id) {
		return getEntityManager().find(Ingredient.class, id);
	}

	@Override
	public void save(Ingredient t) {
		getEntityManager().persist(t);
	}

	@Override
	public void update(Ingredient t) {
		if (t.getId() == null) {
			// TODO Exception a realizar
		} else {
			getEntityManager().merge(t);
		}

	}

	@PersistenceContext
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	public EntityManager getEntityManager() {
		return entityManager;
	}

	@Override
	public List<Ingredient> findAllIngredientByName(String name) {
		Query query = getEntityManager().createQuery(
				"SELECT i " + "FROM Ingredient i WHERE i.name LIKE :name")
				.setParameter("name", "%" + name + "%");
		return (List<Ingredient>) query.getResultList();
	}

}
